package lab2;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
import java.util.ArrayList;
import java.io.*;

public class WordLadder {
	private static Graph graph;

	public static void main(String[] args) {
		StringBuilder sb = new StringBuilder();
		ArrayList<String> input = new ArrayList<String>();
		try {
			ArrayList<String> vertices = new ArrayList<String>();
			FileInputStream is = new FileInputStream(args[0]);
			BufferedReader br = new BufferedReader(new InputStreamReader(is));
			String line = "";
			while ((line = br.readLine()) != null) {
				vertices.add(line);
			}

			graph = new Graph(vertices);

			is = new FileInputStream(args[1]);
			br = new BufferedReader(new InputStreamReader(is));
			line = "";
			String[] str;
			while ((line = br.readLine()) != null) {
				str = line.split(" ");
				input.add(str[0]);
				input.add(str[1]);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

		int[] distance = new int[input.size() / 2];
		String[] children;
		Queue<String> queue = new LinkedList<String>();
		HashMap<String, String> visited = new HashMap<String, String>();
		String node;
		String wordToFind;
		int steps;
		for (int i = 0; i < input.size(); i += 2) {
			steps = -1;
			wordToFind = input.get(i + 1);
			// System.out.print(" " + i);
			queue.clear();
			visited.clear();
			queue.add(input.get(i));
			while (!queue.isEmpty()) {
				node = queue.remove();
				if (node.compareTo(wordToFind) != 0) {
					children = graph.get(node);
					if (children != null) {
						for (int j = 0; j < children.length; j++) {
							if (!visited.containsKey(children[j])
									&& children[j] != null && children[j] != "") {
								queue.add(children[j]);
								visited.put(children[j], node);
							}
						}
					}
				} else {
					queue.clear();
					steps++;
					while (wordToFind.compareTo(input.get(i)) != 0) {
						wordToFind = visited.get(wordToFind);
						steps++;
					}
				}
			}
			distance[i / 2] = steps;
		}
		System.out.println();
		for (int i = 0; i < distance.length; i++) {
			sb.append(distance[i]);
			// if (i != distance.length - 1)
			sb.append('\n');
			System.out.println(distance[i]);
		}
		String result = sb.toString();

		sb = new StringBuilder();
		try {
			FileInputStream is = new FileInputStream(args[2]);
			BufferedReader br = new BufferedReader(new InputStreamReader(is));
			String line = "";
			String testLine = "";
			while ((line = br.readLine()) != null) {
				sb.append(line);
				sb.append('\n');
			}
			String fileResult = sb.toString();
			if (fileResult.compareTo(result) != 0) {
				System.out.println('\n' + "Not equal");
			} else {
				System.out.println('\n' + "Equal");
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}